/*
 * Filename: DBAccess.java
 * Description: This class provides a channel to connect and access the database
 */

package edu.usc.libtalk.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import android.util.Log;

public class DBAccess {
	private static DBAccess DBObject;
	private Connection con;
	
	/* Database configuration */
	private static final String url = "jdbc:mysql://greenbay.usc.edu:3306/libtalk";  
	private static final String user = "libtalk";  
	private static final String password = "libtalk";  		
	
	/** A private Constructor prevents any other class from instantiating. */
	private DBAccess() {

	}
	
	public static synchronized DBAccess getDBObject() {
		if (DBObject == null) {
			DBObject = new DBAccess();
		}
		return DBObject;
	}
	
	public Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}
	
	public int connectDB() {
        
		try { 
        	Class.forName ("com.mysql.jdbc.Driver").newInstance();
       	 	con = DriverManager.getConnection(url, user, password);
       	 	
       	 	/* Test Query */
       	 	Statement st = con.createStatement();  
       	 	ResultSet rs = st.executeQuery("select * from User");  
       	 	while(rs.next()) {  
       	 		Log.e("DBAccess", rs.getString("uname") );  
       	 	} 
       	 	
		} catch (Exception e) {
			Log.e("DBAccess", e.getMessage());
			return -1;
		}  
		
		return 0;
	}
	
	public int disconnectDB() {

        if (con != null)
		{
			try {
				con.close ();                
            }
			catch (Exception e) 
			{ 
				Log.e("DBAccess", e.getMessage());
				return -1;
            }
        }		
		
		return 0;
	}
}